import os
import time
import requests
from datetime import datetime
import math
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib

listJZ = []
list_time = []


def get_gz_history(fund_code):
    for i in range(1, 7):  # 爬取12个月的历史净值
        url = f"http://api.fund.eastmoney.com/f10/lsjz?fundCode={fund_code}&pageIndex={i}&pageSize=20"
        headers = {
            'Referer': 'http://fundf10.eastmoney.com',
            'User-Agent': 'Mozilla/5.0'
        }
        r = requests.get(url, headers=headers, timeout=60)
        data = r.json()['Data']['LSJZList']
        for get_ls_num in range(len(data)):
            listJZ.append(float(data[get_ls_num]['DWJZ']))  # 保存所有历史净值
            list_time.append(data[get_ls_num]['FSRQ'])  # 保存最近更新的历史净值的时间


def get_near_xh(code, jj_rc):
    try:
        jj_code = jj_rc['基金代码'].values
        near_xh = []
        get_gz_history(jj_code[code])
        print(f'数据天数:{len(listJZ)}')
        day = len(listJZ) - 1
        for j in range(len(listJZ)):
            price = listJZ[day]
            if day < len(listJZ) - 5:
                ma5 = sum(listJZ[-(len(listJZ) - day - 1):][:5]) / 5
            else:
                ma5 = 0
            if day < len(listJZ) - 10:
                ma10 = sum(listJZ[-(len(listJZ) - day - 1):][:10]) / 10
            else:
                ma10 = 0
            if day < len(listJZ) - 20:
                ma20 = sum(listJZ[-(len(listJZ) - day - 1):][:20]) / 20
            else:
                ma20 = 0
            if ma5 != 0 and ma20 != 0 and ma10 != 0:
                if day < len(listJZ) - 6:  # 确保有足够数据计算前一天的MA
                    today_ma5 = sum(listJZ[-(len(listJZ) - day):][:5]) / 5  # 今天的MA5
                else:
                    today_ma5 = 0
                if day < len(listJZ) - 21:  # 确保有足够数据计算前一天的MA20
                    today_ma20 = sum(listJZ[-(len(listJZ) - day):][:20]) / 20  # 今天的MA20
                else:
                    today_ma20 = 0
                my_bz_c = math.sqrt(
                    sum((x - ma20) ** 2 for x in listJZ[-(len(listJZ) - day - 1):][:20]) / 20)  # 计算20日标准差(波动率)
                upper_band = ma20 + 2 * my_bz_c  # 布林带上轨
                # 💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦
                if today_ma5 != 0 and today_ma20 != 0:
                    # 金叉条件：今日ma5>ma20 且 昨日ma5<=ma20
                    if ma5 < ma20 and today_ma5 > today_ma20 and price < upper_band:
                        near_xh.append(f'💰金叉({list_time[day]})')
                    # 死叉条件：今日ma5<ma20 且 昨日ma5>=ma20
                    elif ma5 > ma20 and today_ma5 < today_ma20:
                        near_xh.append(f'💀死叉({list_time[day]})')
                # 💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦💦
            # ============================================================
            day = day - 1
        listJZ.clear()
        if near_xh:
            return near_xh[-1]
    except Exception as a:
        print(f'出错了：{a}')
        return "计算错误，跳过该基金"
